package main.java.com.lee.juc.aqs;

import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;


/**
 * 自定义继承aqs实现一把独占锁
 *
 * @author winston
 * @date 2022/02/14
 */
public class SimpleAQSLock implements Lock {

    private Sync sync;

    public SimpleAQSLock() {
        this.sync = new Sync();
    }

    static class Sync extends AbstractQueuedSynchronizer{
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                System.out.println("加锁成功");
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            if (getExclusiveOwnerThread() == Thread.currentThread() && getState() != 0) {
                setExclusiveOwnerThread(null);
                setState(0);
                System.out.println("释放锁成功");
                return true;
            }
            return false;
        }

    }


    @Override
    public void lock() {

        for(;;){
            if (sync.tryAcquire(0)) {
                return;
            }
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        for(;;){
            if (sync.tryRelease(0)) {
                return;
            }
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
